package main

import (
	"gopkg.in/yaml.v2"
	"log"
	"flag"
	"io/ioutil"
	"github.com/jinzhu/gorm"
	"moss/conf"
	"moss/meta"
	"os"
	"path"
)

type AccessKey struct {
	AccessKeyId     string
	AccessKeySecret string
	AuthID          string
	DisplayName     string
}


func main() {
	passwdPath := flag.String("passwd-file", "passwd.yml", "YAML document location")
	dbPath := flag.String("db-file", "data/moss.db", "Database file location")
	flag.Parse()

	yamlDoc, err := ioutil.ReadFile(*passwdPath)
	if err != nil {
		log.Fatalln(err)
	}

	keyList := make([]AccessKey, 0)

	err = yaml.Unmarshal(yamlDoc, &keyList)
	if err != nil {
		log.Fatalln(err)
	}

	log.Println(keyList)

	_, err = os.Stat(*dbPath)
	if os.IsNotExist(err) {
		err = os.MkdirAll(path.Dir(*dbPath), os.ModePerm)
	}

	if err != nil {
		log.Fatalln("os.Stat or os.MkdirAll failed:", err)
	}

	dbHook, err := gorm.Open("sqlite3", *dbPath)
	if err != nil {
		log.Fatalln(err)
	}

	if !dbHook.HasTable(&meta.Auth{}) {
		dbHook.CreateTable(&meta.Auth{})
	}

	for _, keyEntry := range keyList {
		dbHook.Create(&meta.Auth{
			AccessKeyId:     keyEntry.AccessKeyId,
			AccessKeySecret: keyEntry.AccessKeySecret,
			AuthID:          keyEntry.AuthID,
			DisplayName:     keyEntry.DisplayName,
			Status:          conf.AccessKeyActive})
	}

	dbHook.Close()
}
